import Vue from 'vue'

/*
*  用于像安卓app一样响应back事件，关闭弹窗，阻止直接退出页面
*
* */
function isWeixinBrowser () {
  var agent = navigator.userAgent.toLowerCase()
  if (agent.match(/MicroMessenger/i) == 'micromessenger') {
    return true
  } else {
    return false
  }
}

const isWx = true || isWeixinBrowser()
if (!sessionStorage.HaveBeenTo && isWx) {
  sessionStorage.HaveBeenToFirstHref = location.href
  history.pushState(undefined, undefined, location.href)
}

/* 为了阻止第一页回退,并关闭首页弹窗 只支持微信浏览器  */
function quit (router, $navigation) {
  window.onpopstate = function ({state}) {
    if (!isWx) return
    //console.log(state)
    const route = $navigation.getRoutes()
    if (route.length == 1 && state == null && location.href == sessionStorage.HaveBeenToFirstHref) { // 判断是微信浏览器就阻止退出
      const currentView = getCurrentView()
      const closePop = currentView && currentView.closePop || function () {return true}
      history.pushState(undefined, undefined, sessionStorage.HaveBeenTo)
      if (Vue.$vux.confirm.isVisible()) {
        Vue.$vux.confirm.hide()
      } else if (closePop && closePop()) {
        // 如果没有首页则替换到首页
        if (route[0].split('?')[0] !== 'user') {
          router.replace({name: 'user'})
          sleep().then(() => sessionStorage.HaveBeenTo = location.href)
        } else {
          Vue.$vux.confirm.show({
            title: '退出程序吗？',
            onConfirm () {
              typeof(WeixinJSBridge) !== 'undefined' && WeixinJSBridge.call('closeWindow')
            }
          })
        }
      }
    }
  }

  /* 保存解析后的首页url(被加入VNK的url) begin */
  sessionStorage.HaveBeenTo || router.beforeEach(function firstFun (to, from, next) {
    if (to.query.VNK) {
      sessionStorage.HaveBeenTo = location.href
      router.beforeHooks.splice(router.beforeHooks.indexOf(firstFun), 1)
    }
    next()
  })
  /* 保存解析后的首页url(被加入VNK的url) end */
}

export default quit